import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { AppException } from '../exceptions/AppException';
import { HttpStatusCodeEnum } from '../enums/http-status-code.enum';
import { IS_PUBLIC_KEY } from '../auth/auth.decorator';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  private readonly logger = new Logger(RoleGuard.name);

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    // 获取路由上的角色信息
    const roles = this.reflector.getAllAndOverride<string[]>('roles', [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!roles) {
      return true; // 如果没有角色要求，则默认通过
    }
    const request = context.switchToHttp().getRequest();

    const user = request['user']; // 从请求中获取解码后的用户信息

    if (!user) {
      throw new AppException(HttpStatusCodeEnum.FORBIDDEN);
    }
    this.logger.log(
      `当前接口${request.url}需要${roles}权限,已有权限${user.role}`,
    );

    // 检查用户角色是否在路由要求的角色列表中
    return roles.some((role) => user.role?.includes(role)); // 假设 user.roles 是一个包含角色的数组
  }
}
